package com.topone.permission.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.topone.permission.dao.SysUserMapper;
import com.topone.permission.dao.UserAndRoleMapper;
import com.topone.permission.entity.SysUser;
import com.topone.permission.entity.UserAndRole;


@Service
public class SysUserService {
	
	@Autowired
	SysUserMapper sysUserMapper;
	
	@Autowired
	UserAndRoleMapper userAndRoleMapper ;
	
		//通过phone获取user
		public SysUser findByPhone(String phone){
			Assert.hasText(phone, "The phone is null");
			return sysUserMapper.findByPhone(phone);
		}
		
		//创建user
		public void save(SysUser user){
			Assert.notNull(user,"SysUser is null");
			Assert.hasText(user.getPassword(),"password is null");
			Assert.hasText(user.getUserName(),"userName is null");
			Assert.hasText(user.getHandPhone(),"phone is null");
			user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
			sysUserMapper.save(user);
		}
		
		//通过公司获取旗下员工数
		public List<SysUser> findByCompanyCode(String companyCode){
			Assert.hasText(companyCode,"companyCode is null");
			return sysUserMapper.findByCompanyCode(companyCode);
		}
		
		//修改用户角色
		public void editUserWithRole(Long userId,List<Long> roleIdList){
			Assert.notNull(userId, "The SysUser is null");
			Assert.notEmpty(roleIdList,"RoleId List is empty");
			SysUser user = new SysUser();
			user.setUserId(userId);
			relationship(user, roleIdList);
		}
		
		private void relationship(SysUser user,List<Long> roleIdList){
			Assert.notNull(user, "The SysUser is null");
			if(!CollectionUtils.isEmpty(roleIdList)){
				List<UserAndRole> list=new ArrayList<>();
				for (Long roleId : roleIdList) {
					UserAndRole rp = new UserAndRole();
					rp.setUserId(user.getUserId());
					rp.setRoleId(roleId);
				}
				if(!CollectionUtils.isEmpty(list)){
					userAndRoleMapper.detele(new UserAndRole(user.getUserId()));
					userAndRoleMapper.batchsave(list);
				}
			}
		}
		
}
